package com.idopartx.phonelightning.ui.base

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import me.yokeyword.fragmentation.SupportFragment
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<DB : ViewDataBinding> : Fragment() {

    var binding: DB? = null
//    var viewModel: VM? = null

    @LayoutRes
    abstract fun initLayoutResId(): Int

    abstract fun onCreate()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, initLayoutResId(), container, false)
        binding?.lifecycleOwner = this

//        val vmClass =
//            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
//        viewModel = ViewModelProvider(this).get(vmClass)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onCreate()
    }


    fun requestForResult(block: (ActivityResult) -> Unit): ActivityResultLauncher<Intent> {
        return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            block(result)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding = null
    }
}